#include "uni_hal_adc.h"
#include "unione_lite.h"
#include "DrvUART010.h"
#include <rtthread.h>
#include <string.h>

#define ADC_PRINT(format, ...)     rt_kprintf("[HAL_ADC]%s %d:"format, __FUNCTION__, __LINE__, ##__VA_ARGS__)

int uni_hal_adc_init(void)
{
  ftadc_init();
  return 0;
}

int uni_hal_adc_init_irq(void)
{
  ftadc_init_irq();
  return 0;
}

int uni_hal_adc_get_value(u8 channel, int *value)
{
  if(channel != 2 && channel != 3) {
    ADC_PRINT("failed, just support channel2 and channel3\r\n");
    return -1;
  }

  *value = ftadc_get_data(channel);
  return 0;
}

int uni_hal_register_callback(u8 channel, adc_callback func)
{
  if(channel != 2 && channel != 3) {
    ADC_PRINT("failed, just support channel2 and channel3\r\n");
    return -1;
  }
  if(func == NULL){
    ADC_PRINT("func is NULL\n");
    return -1;
  }
  g_adc_cb[channel] = func;
  return 0;
}

/*********************************************************************************************
channel: just support channel-2 and channel-3
thre_event_num: range 0~15
is_high_thre: 1:high, 0:low
thre_value: range (0~0xfff)
  when is_high_thre = 1:over thre_value will trigger interrupt, 0xfff will disable the function
  when is_high_thre = 0:below threshold threshold_l trigger interrupt, 0x0000 will disable the function
**********************************************************************************************/
int uni_hal_adc_config_channel(u8 channel, int event_index, u8 thres_type, u16 thres_value)
{
  if(channel != 2 && channel != 3) {
    ADC_PRINT("failed, just support channel2 and channel3, now is %d \r\n", channel);
    return -1;
  }
  if (event_index > 15 || event_index < 0) {
    ADC_PRINT("failed, thres event should range in (0~15), now is %d \r\n", event_index);
    return -1;
  }
  if (thres_value > 0xfff || thres_value < 0) {
    ADC_PRINT("failed, thres_value should range in (0~0xfff), now is %d \r\n", thres_value);
    return -1;
  }

  ftadc_set_threshold(channel, event_index, (!!thres_type), thres_value);

  return 0;
}

/*********************************************************************************************
channel: just support channel-2 and channel-3
debounce_count: how much count to trigger cb
debounce_gap: the value detla in gap will countdown debounce_count
**********************************************************************************************/
void uni_hal_adc_set_debounce(u8 channel, int debounce_count, int debounce_gap) {
  if(channel != 2 && channel != 3) {
    ADC_PRINT("failed, just support channel2 and channel3, now is %d \r\n", channel);
    return;
  }
  g_debounce_count[channel] = debounce_count;
  g_debounce_gap[channel] = debounce_gap;
}

void uni_hal_adc_start(void)
{
  ftadc_adc_start();
}

void uni_hal_adc_stop(void)
{
  ftadc_adc_stop();
}

int uni_hal_adc_final(void)
{
  ftadc_final();
  memset(g_adc_cb, 0, sizeof(adc_callback)*CHANNEL_NUMS);
  return 0;
}


